package dataserver

import (
	"context"
	"core/corestruct"
	"core/datetime"
	"core/id"
	mymongo "core/mongo"
	"core/server/baseserver"
	"github.com/dubbogo/gost/log/logger"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo/options"
	"iotall/iotcore/entity"
	"iotall/iotproxy/proxyconfig"

	"go.mongodb.org/mongo-driver/mongo"
	"time"
)

type commDataServer struct {
	baseserver.BaseServer
	list  *corestruct.Queue
	today string
}

func (p *commDataServer) Add(reqid, CommPortId int64, Sid, Method, Data, Memo string) {
	var m = &entity.CommData{
		Id:          reqid,
		Sid:         Sid,
		Method:      Method,
		CrtDt:       time.Now(),
		Data:        Data,
		Memo:        Memo,
		CommPortId:  CommPortId,
		CommProxyId: proxyconfig.Config.Id,
	}
	p.AddData(m)
}
func (p *commDataServer) AddData(m *entity.CommData) {
	if m.Id == 0 {
		m.Id = id.NewId()
	}
	m.CommProxyId = proxyconfig.Config.Id

	p.list.Push(m)
}
func (p *commDataServer) Save() {
	var l = p.list.PopAll()
	if len(l) == 0 {
		return
	}
	var today = datetime.FormatDate(time.Now())
	var colname = "CommData" + p.today
	if today != p.today {
		p.today = today
		colname = "CommData" + p.today
		mymongo.Db.CreateCollection(context.Background(), colname)
		var im = mongo.IndexModel{
			Keys:    bson.D{{"sid", 1}},
			Options: options.Index().SetUnique(false),
		}
		var col = mymongo.Db.Collection(colname)
		col.Indexes().CreateOne(context.Background(), im)
	}

	var col = mymongo.Db.Collection(colname)
	var _, err = col.InsertMany(context.Background(), l)
	if err != nil {
		logger.Errorf("SaveCommData错误 %v", err)
	}
}
func (p *commDataServer) DoInterval() {

	p.Save()
	if time.Now().Minute() == 59 && time.Now().Second() >= 55 {
		for time.Now().Second() >= 55 {
			time.Sleep(time.Millisecond * 100)
		}
		p.Save()
	}

}
func (p *commDataServer) Start() {
	p.list = &corestruct.Queue{}

	p.BaseServer.DoInterval = p.DoInterval
	p.BaseServer.DoClose = p.DoInterval

	p.BaseServer.Start()
}

var (
	CommDataServer *commDataServer
)

func init() {
	CommDataServer = &commDataServer{
		BaseServer: baseserver.BaseServer{Interval: 5000, Name: "通讯数据上传服务"},
	}
	CommDataServer.Start()
}
